package nodes;

import java.util.HashMap;
import java.util.Map;

import compiler.Compiler;
import compiler.SymbolTable;

import descriptors.AbstractDescr;
import descriptors.RecordDescr;
import descriptors.TypeDescr;
import descriptors.VarDescr;

public class RecordNode extends AbstractNode {

	private ListNode<FieldListNode> fieldList;

	public RecordNode(ListNode<FieldListNode> fieldList, int line, int column) {
		super(line, column);
		this.fieldList = fieldList;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public AbstractDescr compile(
			SymbolTable symbolTable, Compiler compiler) {
		Map<String,AbstractDescr> recSymbolTable=new HashMap<String,AbstractDescr>();
		int sizeRec=0;
		int addressRec=0;
		for(FieldListNode flNode: fieldList){
			AbstractDescr typeDescr=null;
			AbstractNode type=flNode.type();
			if(type instanceof IdentNode){
				typeDescr=symbolTable.search(compiler.level(), ((IdentNode) type).ident());
				// TODO: Check without!!!
				//if (typeDescr== null){
				//	typeDescr= new TypeDescr(1,compiler.level(),((IdentNode) type).ident());
				//}
			} // Case of record or array
			else {
				typeDescr=type.compile(symbolTable, compiler);
			}
			for(IdentNode ident:flNode.identList()){
				recSymbolTable.put(ident.ident(), new VarDescr(compiler.level(), addressRec, false, typeDescr));
				addressRec += typeDescr.getSize();
				sizeRec += typeDescr.getSize();
			}
		}
		return new RecordDescr(sizeRec,recSymbolTable);
	}

	@Override
	public void print() {
		trace("RecordNode");
		if (fieldList != null)
			fieldList.print();
		unindent();
	}

}
